package identify

// #include "yoyoai_helper.h"
import "C"
import (
	"fmt"
	"unsafe"
)

// 枚举识别模型返回的状态码
var statusCodeMap = map[int]error{
	C.STATUS_RECOG_SUCCESS:         nil,
	C.STATUS_RECOG_ERROR:           ErrRecog,
	C.STATUS_VALIDATION_ERROR:      ErrValidation,
	C.STATUS_ACCELERATION_ERROR:    ErrAcceleration,
	C.STATUS_PREPROCESS_ERROR:      ErrPreprocess,
	C.STATUS_POSTPROCESS_ERROR:     ErrPostprocess,
	C.STATUS_RECOG_PARA_ERROR:      ErrRecogPara,
	C.STATUS_RECOG_MEM_ERROR:       ErrRecogMem,
	C.STATUS_RECOG_DATA_ERROR:      ErrRecogData,
	C.STATUS_RECOG_PIPILINE_ERROR:  ErrRecogPipiline,
	C.STATUS_RECOG_FILE_ERROR:      ErrRecogFile,
	C.STATUS_RECOG_KEY_EMPTY_ERROR: ErrKeyEmpty,
	C.STATUS_JPEG_DATA_CORRUPTED:   ErrJpegDataCorrupted,
}

// convertStatusCode 转换状态码
func convertStatusCode(code int) error {
	// 查找状态码映射
	if v, ok := statusCodeMap[code]; ok {
		return v
	}
	// 返回原始异常状态码
	return fmt.Errorf("unknown error, response status code %d", code)
}

// Processor 处理器类型
type Processor int

const (
	ProcessorCPU Processor = C.CPU // CPU处理器
	ProcessorNPU Processor = C.NPU // NPU处理器
	ProcessorGPU Processor = C.GPU // GPU处理器
)

// FeatureMode 特征模式类型
type FeatureMode int

const (
	// FeatModeGeneral 通用模型
	FeatModeGeneral FeatureMode = C.GENERAL
	// FeatModeFresh 生鲜模型
	FeatModeFresh FeatureMode = C.FRESH
	// FeatModeSnack 零食模型
	FeatModeSnack FeatureMode = C.SNACK
)

// CRecogMat 转换为C类型RecogMat*
func (p *ImageInfo) CRecogMat() (*C.RecogMat, func()) {
	// 构建裁剪信息
	var imgCrop *C.RecogRegionCrop = C.mallocRecogRegionCrop()
	// 是否需要裁剪
	if p.Area != nil {
		imgCrop.x0 = C.uint32_t(p.Area.X0)
		imgCrop.y0 = C.uint32_t(p.Area.Y0)
		imgCrop.x1 = C.uint32_t(p.Area.X1)
		imgCrop.y1 = C.uint32_t(p.Area.Y1)
		imgCrop.x2 = C.uint32_t(p.Area.X2)
		imgCrop.y2 = C.uint32_t(p.Area.Y2)
		imgCrop.x3 = C.uint32_t(p.Area.X3)
		imgCrop.y3 = C.uint32_t(p.Area.Y3)
	} else {
		imgCrop.x0 = 0
		imgCrop.y0 = 0
		imgCrop.x1 = 0
		imgCrop.y1 = 0
		imgCrop.x2 = 0
		imgCrop.y2 = 0
		imgCrop.x3 = 0
		imgCrop.y3 = 0
	}

	// 赋值图像信息
	imgMat := C.mallocRecogMat()
	imgMat.format = C.FMT_JPEG
	imgMat.dataSize = C.uint32_t(len(p.Data))
	imgMat.data = (*C.uchar)(C.CBytes(p.Data))
	imgMat.coord = imgCrop

	// 构建释放方法回调
	freeFunc := func() {
		if imgCrop != nil {
			C.free(unsafe.Pointer(imgCrop))
		}
		if imgMat.data != nil {
			C.free(unsafe.Pointer(imgMat.data))
		}
		if imgMat != nil {
			C.free(unsafe.Pointer(imgMat))
		}
	}

	// 返回*C.RecogMat结构 和 释放内存回调函数
	return imgMat, freeFunc
}
